import React from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Alert,
  ScrollView,
} from 'react-native';
import { useTranslation } from 'react-i18next';

const LanguageSwitcher = ({ style }) => {
  const { t, i18n } = useTranslation();

  const languages = [
    { code: 'en', name: 'English', nativeName: 'English', flag: '🇺🇸' },
    { code: 'zh-CN', name: 'Simplified Chinese', nativeName: '简体中文', flag: '🇨🇳' },
    { code: 'zh-TW', name: 'Traditional Chinese', nativeName: '繁體中文', flag: '🇹🇼' },
    { code: 'ko', name: 'Korean', nativeName: '한국어', flag: '🇰🇷' },
    { code: 'ja', name: 'Japanese', nativeName: '日本語', flag: '🇯🇵' },
  ];

  const changeLanguage = (languageCode) => {
    const selectedLang = languages.find(lang => lang.code === languageCode);
    Alert.alert(
      t('settings.language'),
      `${t('common.confirm')} ${selectedLang?.nativeName}?`,
      [
        {
          text: t('common.cancel'),
          style: 'cancel',
        },
        {
          text: t('common.confirm'),
          onPress: () => {
            i18n.changeLanguage(languageCode);
          },
        },
      ]
    );
  };

  return (
    <View style={[styles.container, style]}>
      <Text style={styles.label}>{t('settings.language')}</Text>
      <ScrollView horizontal showsHorizontalScrollIndicator={false}>
        <View style={styles.languageButtons}>
          {languages.map((language) => (
            <TouchableOpacity
              key={language.code}
              style={[
                styles.languageButton,
                i18n.language === language.code && styles.activeLanguageButton,
              ]}
              onPress={() => changeLanguage(language.code)}
            >
              <Text style={styles.flag}>{language.flag}</Text>
              <Text
                style={[
                  styles.languageText,
                  i18n.language === language.code && styles.activeLanguageText,
                ]}
              >
                {language.nativeName}
              </Text>
            </TouchableOpacity>
          ))}
        </View>
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 16,
  },
  label: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 12,
    color: '#333',
  },
  languageButtons: {
    flexDirection: 'row',
    gap: 12,
  },
  languageButton: {
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#ddd',
    backgroundColor: '#f9f9f9',
    alignItems: 'center',
    minWidth: 100,
  },
  activeLanguageButton: {
    backgroundColor: '#007AFF',
    borderColor: '#007AFF',
  },
  flag: {
    fontSize: 20,
    marginBottom: 4,
  },
  languageText: {
    fontSize: 12,
    color: '#666',
    textAlign: 'center',
  },
  activeLanguageText: {
    color: '#fff',
    fontWeight: '600',
  },
});

export default LanguageSwitcher;